/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.cax.service.impl;

import cn.hutool.core.util.IdUtil;
import com.comac.ins.cax.domain.CaxFileInfo;
import com.comac.ins.cax.mapper.CaxFileInfoMapper;
import com.comac.ins.cax.service.ICaxFileInfoService;
import com.comac.ins.cax.utils.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author yk
 * @desc CAX转换文件service
 * @date 2024-06-19 11:00
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CaxFileInfoServiceImpl implements ICaxFileInfoService {

    private final CaxFileInfoMapper caxFileInfoMapper;

    private static final String UPLOAD_PATH = "/data/file/";

    @Override
    public CaxFileInfo uploadFile(MultipartFile file) {
        if (file == null || "".equals(file.getOriginalFilename())) {
            return null;
        }
        try {
            String fileName = file.getOriginalFilename();
            Assert.notNull(fileName, "fileName字段非法");
            String fileExt = FileUtils.getFileExt(fileName);
            long size = file.getSize();
            String filePath = createFilePath();
            // 将文件保存到服务器
            Path destinationFile = Paths.get(filePath, fileName);
            Files.copy(file.getInputStream(), destinationFile);
            // 保存DB文件记录
            CaxFileInfo caxFileInfo = new CaxFileInfo();
            caxFileInfo.setName(fileName);
            caxFileInfo.setPath(filePath + "/" + fileName);
            caxFileInfo.setType(fileExt);
            caxFileInfo.setSize(String.valueOf(size));
            caxFileInfoMapper.insert(caxFileInfo);
            return caxFileInfo;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建文件上传路径
     *
     * @return 文件上传路径
     * @throws IOException 异常
     */
    public String createFilePath() throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(new Date());
        String filePath = UPLOAD_PATH + currentDate + "/" + IdUtil.simpleUUID() + "/";
        // 创建目标目录如果它不存在
        Files.createDirectories(Paths.get(filePath));
        return filePath;
    }

    @Override
    public CaxFileInfo queryById(Long id) {
        return caxFileInfoMapper.selectById(id);
    }
}
